<template>
  <div class="main-page">
    <PageSearch :search-form-config="searchFormConfig" :form-data.sync="formData" @searchBtnClick="handleSearch" />
    <el-row type="flex" justify="end">
      <el-button type="primary" icon="el-icon-plus" size="medium" @click="handleCreateNew">
        新建设备
      </el-button>
      <el-button type="primary" icon="el-icon-download" size="medium" @click="handleDownload">
        下载模版
      </el-button>
      <el-upload :http-request="customRequest" action="">
        <el-button :loading="exportLoading" style="margin-left: 10px" type="primary" icon="el-icon-upload2" size="medium">
          批量导入
        </el-button>
      </el-upload>
    </el-row>
    <PageContent ref="pageContent" :form-data="formData" :content-table-config="contentConfig">
      <template #image="scope">
        <el-image v-if="scope.row.picture" style="width: 60px; height: 60px" :src="getPicUrl(scope.row.picture)" :preview-src-list="getPicUrlList(scope.row.picture)">
        </el-image>
        <span v-else>无</span>
      </template>

      <template #deviceType="scope">
        {{
          scope.row.deviceType == 1
            ? "TV盒子"
            : scope.row.deviceType == 2
              ? "X86"
              : scope.row.deviceType == 3
                ? "路由器":"未知"
        }}
      </template>
      <template #settlementType="scope">
        {{
          scope.row.settlementType == 0 ? '默认结算' : '买断'
        }}
      </template>

      <template #operate="{ row }">
        <el-button type="text" size="small" icon="el-icon-money" @click="handleViewIncome(row)">
          收益
        </el-button>
        <el-button v-show="row.belongUserName" type="text" size="small" icon="el-icon-search" @click="handleDeviceRealTimeInfo(row)">
          实时信息
        </el-button>
        <el-button v-show="row.belongUserName !== '' && row.belongUserName !== null" type="text" size="small" icon="el-icon-scissors" @click="handleUnbinding(row)">
          解绑
        </el-button>
        <el-button type="text" size="small" icon="el-icon-edit" @click="handleEdit(row)">
          编辑
        </el-button>
        <el-button v-show="row.belongUserName && row.deviceType == 2" type="text" size="small" icon="el-icon-scissors" @click="pressureTestResultHandle(row)">
          测试结果
        </el-button>
        <el-button v-show="row.belongUserName && row.deviceType == 2" type="text" size="small" icon="el-icon-scissors" @click="dialingTestResultHandle(row)">
          拨号结果
        </el-button>
        <el-button type="text" size="small" icon="el-icon-delete" class="delete-btn" @click="handleDelete(row)">
          删除
        </el-button>
        <el-button type="text" size="small" icon="el-icon-sort" @click="switchDispatchType(row)">
          切换调度范围
        </el-button>
      </template>
    </PageContent>
    <el-dialog title="切换调度范围" :visible.sync="dialogVisible2" width="30%">
      <el-select v-model="dispatchType" placeholder="请选择">
        <el-option :value="0" :label="'全国'"></el-option>
        <el-option :value="1" :label="'本省'"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="switchDispatchTypeSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <PageModal :modal-form-data="modalFormData" :modal-form-config="modalFormConfig" :visible.sync="dialogVisible" :title="title" :btn-loading="confirmBtnLoading" @confirm="handleConfirm">
      <el-form label-width="100px" label-suffix=":">
        <el-form-item v-if="title === '编辑设备'" label="结算方式">
          <el-select v-model="modalFormData.settlementType" style="width: 100%;" placeholder="请选择结算方式">
            <el-option label="默认结算" :value="0"></el-option>
            <el-option label="买断" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备图片">
          <UploadFileImg :file-list="fileList" />
        </el-form-item>
      </el-form>
    </PageModal>

    <!-- 设备实时信息 -->
    <device-info v-if="showDeviceInfo" :show.sync="showDeviceInfo" :sn="sn"></device-info>
    <!-- 收益明细 -->
    <device-income v-if="showIncome" :show.sync="showIncome" :sn="sn"></device-income>

    <pressure-test v-if="showPressureTest" :show.sync="showPressureTest" :sn="sn"></pressure-test>
    <dialing-test v-if="showDialingTest" :show.sync="showDialingTest" :sn="sn"></dialing-test>
    <!-- 批量导入 -->
    <MyDialog title="下载模版" show-cancel :visible="exportDialogVisible" :ok-loading="btnLoading" width="600px" @close="exportDialogVisible = false" @ok="handleConfirmDownLoad">
      <el-form ref="modalDownLoadForm" label-width="100px" :model="modalDownLoadData" label-suffix=":" :rules="modalDownLoadRules">
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="modalDownLoadData.deviceType" style="width: 100%" placeholder="请选择设备类型">
            <el-option v-for="item in DEVICE_TYPE" :key="item.value" :label="item.label" :value="item.value" clearable>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </MyDialog>
  </div>
</template>

<script>
import dialogMixin from "@/mixins/dialogMixin";
import { contentConfig } from "./config/content.config";
import { searchFormConfig } from "./config/search.config";
import { modalFormConfig } from "./config/modal.config";
import { DEVICE_TYPE, menus } from "@/config/enum";
import {
  fetchDeviceOnlineStatus,
  fetchSaveDevice,
  fetchDeleteDevice,
  fetchBatchImport,
  recovery,
  switchDispatchTypeReq,
} from "@/api/deviceManage";
import UploadFileImg from "@/components/uploadFileImg/index.vue";
import DeviceInfo from "./deviceInfo.vue";
import DeviceIncome from "./deviceIncome.vue";
import PressureTest from "./pressureTest.vue";
import DialingTest from "./dialingTest.vue";
import localCache from "@/utils/cache";
import { fetchChannelGetList, } from "@/api/trafficPrice";
export default {
  name: "DeviceList",
  components: {
    DeviceInfo,
    DeviceIncome,
    UploadFileImg,
    PressureTest,
    DialingTest
  },
  mixins: [dialogMixin],
  data() {
    return {
      exportLoading: false,
      DEVICE_TYPE,
      modalDownLoadData: {
        deviceType: "",
      },
      modalDownLoadRules: {
        deviceType: [{ required: true, message: "请选择品牌", trigger: "blur" }],
      },
      exportDialogVisible: false,
      showIncome: false,
      fileList: [],
      sn: "",
      title: "新建设备",
      menus,
      contentConfig,
      searchFormConfig,
      modalFormConfig,
      btnLoading: false,
      confirmBtnLoading: false,
      dialogVisible: false,
      dialogVisible2: false,
      showDeviceInfo: false,
      formData: {}, // 搜索表单数据
      modalFormData: {
        sn: "",
        name: "",
        deviceType: "",
        picture: "",
        settlementType:0
      },
      showPressureTest: false,
      showDialingTest: false,
      dispatchType: "",
    };
  },
  computed: {
    getPicUrl() {
      return (data) => {
        return JSON.parse(data)[0]?.absolutePath;
      };
    },
    getPicUrlList() {
      return (data) => {
        const arr = JSON.parse(data);
        if (Array.isArray(arr)) {
          return arr.map((item) => item.absolutePath);
        }
      };
    },
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.fileList = [];
      }
    },
  },
  mounted() {
    this.getTeam();
  },
  methods: {
    switchDispatchType(row) {
      this.dialogVisible2 = true; 
      this.modalFormData = { ...row }
    },
    switchDispatchTypeSubmit() {
      const that = this;
      switchDispatchTypeReq({ sn: that.modalFormData.sn, dispatchType: that.dispatchType }).then(res => {
        if (res.code === 200) {
          that.modalFormData = {}
          that.dialogVisible2 = false;
          that.$message({
            message: '切换成功',
            type: 'success'
          });
        } else {
          that.$message.error(res.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    getTeam() {
      fetchChannelGetList().then((res) => {
        let resArr = [];
        for (let i = 0; i < res.data.length; i++) {
          resArr.push({
            label: res.data[i].name,
            value: res.data[i].id
          })
        }
        this.searchFormConfig.formItems[6].options = resArr;
        this.modalFormConfig.formItems[3].options = resArr;
      });
    },
    customRequest({ file }) {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = () => {
        const formData = new FormData();
        formData.append("fileName", file);
        formData.append("file", fileReader.result);
        this.exportLoading = true;
        fetchBatchImport(formData)
          .then(() => {
            this.$message.success("上传成功");
            this.handleSearch();
          })
          .finally(() => {
            this.exportLoading = false;
          });
      };
    },
    handleDownload() {
      this.exportDialogVisible = true;
    },
    handleConfirmDownLoad() {
      const url = process.env.VUE_APP_BASE_API;

      this.axios({
        method: "get",
        url: url + "/device/templateDownload",
        responseType: "blob",
        params: { deviceType: this.modalDownLoadData.deviceType },
        headers: {
          Authorization: localCache.getCache("token"),
        },
      }).then((res) => {
        this.$download.excel(res.data, "设备模版.xlsx");
      });

    },
    getDeviceOnlineStatus() {
      fetchDeviceOnlineStatus().then((res) => {
        this.deviceList.forEach((item) => {
          this.$set(item, "value", res.data[item.key]);
        });
      });
    },
    handleSearch() {
      this.$refs.pageContent.queryTblMain();
    },
    handleCreateNew() {
      this.title = "新建设备";
      this.modalFormData = {};
      this.fileList = [];
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.title = "编辑设备";
      this.modalFormData = {
        ...row,
      };
      if (this.modalFormData.deviceType) {
        this.modalFormData.deviceType = Number(this.modalFormData.deviceType);
      }
      const arr = row.picture && JSON.parse(row.picture);
      if (Array.isArray(arr)) {
        this.fileList = arr.map((item) => {
          return {
            ...item,
            url: item.absolutePath,
          };
        });
      }

      this.dialogVisible = true;
    },

    //解绑
    handleUnbinding(row) {
      let sn = row.sn;
      this.$confirm("此操作将解绑该设备, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          recovery({ sn }).then(() => {
            this.$message.success(`解绑成功！`);
            this.$refs.pageContent.queryTblMain();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消解绑",
          });
        });
    },

    handleConfirm(data) {
      this.confirmBtnLoading = true;
      const params = { ...this.modalFormData, ...data };
      if (this.fileList.length) {
        params.picture = JSON.stringify(this.fileList);
      }
      fetchSaveDevice(params)
        .then(() => {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.$refs.pageContent.queryTblMain();
          this.dialogVisible = false;
        })
        .finally(() => {
          this.confirmBtnLoading = false;
        });
    },
    handleDelete({ deviceId }) {
      this.$confirm("此操作将删除该设备, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          fetchDeleteDevice({ id: deviceId }).then(() => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.$refs.pageContent.queryTblMain();
          });
        })
        .catch(() => { });
    },
    handleDeviceRealTimeInfo({ sn }) {
      this.sn = sn;
      this.showDeviceInfo = true;
    },
    handleViewIncome({ sn }) {
      this.sn = sn;
      this.showIncome = true;
    },
    pressureTestResultHandle({ sn }) {
      this.sn = sn;
      this.showPressureTest = true;
    },
    dialingTestResultHandle({ sn }) {
      this.sn = sn;
      this.showDialingTest = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.device-static {
  padding: 0 20px;
  margin-top: 20px;
  .icon-point {
    margin-right: 5px;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    display: inline-block;
    position: relative;
    top: -2px;
    &.icon-point-online {
      background-color: #67c23a;
    }
    &.icon-point-offline {
      background-color: #f56c6c;
    }
  }
}
.name {
  text-align: center;
}
.info {
  margin-top: 10px;
  display: flex;
  align-items: center;
  font-size: 30px;
  color: #1d2129;
  text-align: center;
  justify-content: center;
  img {
    margin-right: 8px;
  }
  .unit {
    display: inline-block;
    margin: 6px 0 0 4px;
    font-size: 16px;
  }
}
::v-deep {
  .el-upload-list {
    display: none;
  }
  .el-upload-list__item-name {
    display: none;
  }
}
</style>
